#
#-*- coding: utf-8 -*-
#

from google.appengine.api import xmpp
from google.appengine.ext import db

class Todo(db.Model):
	user = db.StringProperty(required=True)
	desc = db.TextProperty(required=True)

def todoProc(sender,cmd):
	pcmd = cmd.strip()
	pos = pcmd.find(' ')
	
	verb = pcmd
	ar = ''
	if pos != -1 :
		verb = pcmd[:pos]
		ar = pcmd[pos+1:]

	if(verb=='-del'):
		todoDel(sender,ar)
	elif(verb=='-add'):
		todoAdd(sender,ar)
	elif(verb=='-list'):
		todoList(sender)
	elif(verb=='-clear'):
		todoClear(sender)
	else:
		todoHelp(sender)

def todoList(sender):
	query = db.GqlQuery("select * from Todo where user = :1",sender)
	result = query.fetch(1000)
	ret = 'you have %d todo items: ' % len(result)
	for item in result :
		ret += '\n ' + "["+str(item.key().id())+"] " + item.desc
	xmpp.send_message(sender,ret)

def todoAdd(sender,item):
	td = Todo(user=sender,desc=item)
	td.put()
	xmpp.send_message(sender,'todo item added :)')

def todoDel(sender,id):
	query = db.GqlQuery("select * from Todo where user = :1",sender)
	for item in query :
		if str(item.key().id()) == id :
			item.delete()
			xmpp.send_message(sender,'todo item deleted :)')
			return
	
	xmpp.send_message(sender,'todo item not found :(')

def todoClear(sender):
	query = db.GqlQuery("select * from Todo where user = :1",sender)
	db.delete(query)
	xmpp.send_message(sender,'you have no items now')

def todoHelp(sender):
	ret ='''todo has some subcmd :
			\\todo -add newitem
			\\todo -del itemid
			\\todo -list  or \\todo 
			\\todo -clear 
			\\todo -help 
			'''
	xmpp.send_message(sender,ret)
